<?php
namespace Common\ORM\Model;

use Common\Factory;

class AllUser implements \Iterator{

    protected $ids;
    protected $data  = [];
    protected $index;

    public function __construct()
    {
        $db = Factory::getDatabase();
        $result = $db->query('select id from user');
        $this->ids = $result->fetch_all(MYSQLI_ASSOC);
    }

    /**
     * 第三步 返回对象
     * Return the current element
     * @link https://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current()
    {
        $id = $this->ids[$this->index]['id'];
            return Factory::createUser($id);
    }

    /**
     * 第四步
     * Move forward to next element
     * @link https://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next()
    {
        $this->index++;
    }

    /**
     * 第五步
     * Return the key of the current element
     * @link https://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key()
    {
        return $this->index;
    }

    /**
     * 第二步
     * Checks if current position is valid
     * @link https://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid()
    {
        return $this->index < count($this->ids);
    }

    /**
     * 第一步重置迭代器
     * Rewind the Iterator to the first element
     * @link https://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind()
    {
        $this->index = 0;
    }
}